package com.ylt.controller.pay;

import java.security.MessageDigest;
import java.util.Formatter;
import java.util.HashMap;
import java.util.UUID;

import com.utils.gzh.WeChatTask;
import com.utils.redis.RedisUtil;

/**
* @author gzl
* @version date：2021年2月28日
* @description ：
*/
public class JSSDK_Config {

    /**
     * @Description: 前端jssdk页面配置需要用到的配置参数
     * @param @return hashmap {appid,timestamp,nonceStr,signature}
     * @param @throws Exception
     * @author gede
     */
    public static HashMap<String, String> jsSDK_Sign(String url,RedisUtil redisUtil) throws Exception {
        String nonce_str = WXPayUtil.generateNonceStr();//create_nonce_str();
        String appid="wxcb6b51a7bd14fc2b";
        String timestamp= Long.toString(System.currentTimeMillis()/ 1000 );
        if(redisUtil.get(appid+"_jsapi_ticket")==null||"".equals(redisUtil.get(appid+"_jsapi_ticket"))) {
        	WeChatTask wct=new WeChatTask();
        	wct.getToken_getTicket(redisUtil);
        }
        String jsapi_ticket=redisUtil.get(appid+"_jsapi_ticket");
        // 注意这里参数名必须全部小写，且必须有序
        String  string1 = "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + nonce_str
                + "&timestamp=" + timestamp  + "&url=" + url;
		
		  MessageDigest crypt = MessageDigest.getInstance("SHA-1"); crypt.reset();
		  crypt.update(string1.getBytes("UTF-8")); String signature =
		  byteToHex(crypt.digest());
		 
        //String signature=WXPayUtil.generateSignature(data, key);
        HashMap<String, String> jssdk=new HashMap<String, String>();
        jssdk.put("appId", appid);
        jssdk.put("timestamp", timestamp);
        jssdk.put("nonceStr", nonce_str);
        jssdk.put("signature", signature);
        return jssdk;

    }

    private static String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash) {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }

    private static String create_nonce_str() {
        return UUID.randomUUID().toString();
    }

}